import React from 'react';
import './../../form.less';

import moment from 'moment';
import {Button, Icon, message, Row} from 'antd';
import BreadcrumbCustom from "../../../common/BreadcrumbCustom";
import UserTable from "./UserTable";
import UserCreateForm from "./UserForm";
import { Upload } from 'antd';

const props = {
    name: 'files',
    action: '/manage/import/userComment',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };

export default class User extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pageSize: 5,
            total: 0,
            current: 1,
            userType: 2,
            visible: false, //新建窗口隐藏
            dataSource: [],
            selectedRowKeys: [],
            isUpdate: false,
            loading: true,
        };
    }

    //搜索条件
    onChangeLinkUrl = (e) => {
        const value = e.target.value;
        this.setState({
            linkUrl: value,
        })
    };

    pageSizeChange = (current, pageSize) => {
        this.setState({
            pageSize: pageSize,
            current: current
        },() => this.getData())
    }

    getData = () => {
        var url = '/manage/tUser/query'
        const searchCondiction = new Object()
        searchCondiction.pageSize = this.state.pageSize;
        searchCondiction.pageNumber = this.state.current;
        if (this.state.userType) {
            const conditionList = [];
            const condition = {
                code: "userType",
                type: "Number",
                operator: 1,
                value: this.state.userType
            }
            conditionList.push(condition);
            searchCondiction.conditionList = conditionList;
        }
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(searchCondiction)
        }).then((response) => {
            return response.json()
        }).then((res) => {
            console.log(res)
            if (res.code == 200) {
                this.setState({
                    datasource: res.result.list,
                    total:res.result.total,
                    loading: false
                });
            }
        })
    }

    //渲染
    componentDidMount() {
        this.getData();
    }

    //搜索按钮
    btnSearch_Click = () => {
        this.getData();
    };
    //重置按钮
    btnClear_Click = () => {
        this.setState({
            linkUrl: ''
        });
    };
    //新建信息弹窗
    CreateItem = () => {
        this.setState({
            visible: true,
            isUpdate: false,
        });
        const form = this.form;
        form.resetFields();
    };
    //新增
    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);
            values.createtime = moment().format("YYYY-MM-DD hh:mm:ss");
            var url = '/manage/tUser/save'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code == 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                }
            })
            form.resetFields();
            this.setState({
                visible: false,
            });
        });
    };
    //更新修改
    handleUpdate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);
            var url = '/manage/tUser/update'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then((response) => {
                return response.json()
            }).then((res) => {
                if (res.code == 200) {
                    message.success("操作成功")
                    this.getData();
                } else {
                    message.success("操作失败")
                }
            })
            form.resetFields();
            this.setState({
                visible: false,
            });
        });
    };
    //取消
    handleCancel = () => {
        this.setState({visible: false});
    };
    //批量删除
    MinusClick = () => {
        this.state.selectedRowKeys.forEach(index => {
            this.onDelete(this.state.datasource[index].id)
        })
    };
    //单个删除
    onDelete = (tUserId) => {
        console.log(tUserId)
        var url = '/manage/tUser/' + tUserId;
        fetch(url, {
            method: 'DELETE'
        }).then((response) => {
            return response.json()
        }).then((res) => {
            if (res.code == 200) {
                message.success("操作成功")
                this.getData();
            } else {
                message.success("操作失败")
            }
        })
    };
    //点击修改
    editClick = (key) => {
        const tUser = this.state.datasource.filter(tUser => tUser.id == key)[0];
        const form = this.form;
        form.setFieldsValue({
            id:tUser.id,
            tUserName:tUser.tUserName,
            tUserPic:tUser.tUserPic,
            linkUrl:tUser.linkUrl
        });
        this.setState({
            visible: true,
            isUpdate: true,
        });
    };
    //单选框改变选择
    checkChange = (selectedRowKeys) => {
        this.setState({selectedRowKeys: selectedRowKeys});
    };

    render() {
        const questiontxt = () => {
            return (
                <p><Icon type="plus-circle-o"/> : 新建信息<br/>
                    <Icon type="minus-circle-o"/> : 批量删除</p>
            )
        };
        return (
            <div>
                <BreadcrumbCustom paths={['首页', '用户管理']}/>
                <div className='formBody'>
                    {/*<Row gutter={16}>*/}
                        {/*<Col className="gutter-row" sm={8}>*/}
                            {/*<Input*/}
                                {/*placeholder="跳转地址"*/}
                                {/*value={this.state.linkUrl}*/}
                                {/*onChange={this.onChangeLinkUrl}*/}
                            {/*/>*/}
                        {/*</Col>*/}
                    {/*</Row>*/}
                    <Row gutter={16}>
                        <div className='btnOpera'>
                            <Button type="primary" onClick={this.btnSearch_Click}
                                    style={{marginRight: '10px'}}>查询</Button>
                            <Button type="primary" onClick={this.btnClear_Click}
                                    style={{background: '#f8f8f8', color: '#108ee9'}}>重置</Button>
                        </div>
                    </Row>
                    <Upload {...props}>
                        <Button>
                        <Icon type="upload" /> 导入评论
                        </Button>
                    </Upload>
                    <UserTable
                        dataSource={this.state.datasource}
                        checkChange={this.checkChange}
                        onDelete={this.onDelete}
                        editClick={this.editClick}
                        loading={this.loading}
                        pageSizeChange={this.pageSizeChange}
                        total={this.state.total}
                        pageSize={this.state.pageSize}
                        current={this.state.current}
                    />
                    {this.state.isUpdate ?
                        <UserCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                          onCancel={this.handleCancel} onCreate={this.handleUpdate} title="修改类目"
                                          okText="更新"/>
                        : <UserCreateForm ref={(form) => this.form = form} visible={this.state.visible}
                                            onCancel={this.handleCancel} onCreate={this.handleCreate} title="新建类目"
                                            okText="保存"/>}
                </div>
            </div>
        )
    }
}